package snapex.user.controller;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import snapex.core.SnapexApplicationException;
import snapex.core.model.User;
import snapex.core.security.AuthenticationManagerBuilderDelegate;
import snapex.core.utils.QRCodeUtil;
import snapex.user.service.IEmployeeInfoService;

@Slf4j
@Controller
@RequestMapping
public class UserRegistrationController {
	@Autowired
	AuthenticationManagerBuilderDelegate builder;
	
//	@Autowired @Qualifier("jasyptStringEncryptor")
//	StringEncryptor stringEncryptor;
		
	@Autowired
	IEmployeeInfoService employeeHashService;
	
	@Value("${snapex.registerUrl}")
	String registerUrl;
	
	@ApiOperation(value = "QR code for registration")
	@GetMapping(value = "/register/qrcode", produces = MediaType.IMAGE_JPEG_VALUE)
	public ResponseEntity<byte[]> registerQRCode() throws Exception {
				
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		if(auth == null) {
			throw new SnapexApplicationException("Authentication is required");
		}
		
		User user = builder.getUserDetails(auth.getPrincipal());	
				
		String hashKey = employeeHashService.createHash(user);
				
		hashKey = hashKey.substring(0, 10) + System.currentTimeMillis() + hashKey.substring(10);
		
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		
		String url = String.format(registerUrl,URLEncoder.encode(hashKey,"UTF-8"));
		
		log.debug("****registerUrl:{}",url);
		
		QRCodeUtil.encode(url, output);
		
		return new ResponseEntity(output.toByteArray(), HttpStatus.OK);
	}
}
